package org.example.chengyu;

import org.apache.commons.io.FileUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.example.chengyu.entity.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChengYuMain {


    public static void main(String[] args) throws Exception{

        // String text = FileUtils.readFileToString(new File("D:\\北语项目\\3000成语用法词典W.txt"), "utf-8");
        String filePath = "d:\\北语项目\\3000成语用法词典（W）.docx";
        String text = getText(filePath);
        System.out.println(text);
        splitCiTiao(text);
        toFile();

    }


    private static List<CiTiao> ciTiaos = new ArrayList<CiTiao>();

    public static String getText(String filePath) throws Exception
    {
        StringBuilder sb = new StringBuilder();
        try (FileInputStream fis = new FileInputStream(filePath)) {
            XWPFDocument document = new XWPFDocument(fis);
            // 遍历文档中的每一个段落
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                // 遍历段落中的每一个Run
                for (int i=0; i<paragraph.getRuns().size(); i++) {
                    XWPFRun run= paragraph.getRuns().get(i);
                    String text = run.getText(0);
                    if(!run.isStrikeThrough()){
                        if("黑体".equals(run.getFontName())&&i==0) {
                            //这是词条的开始
                            if(text!=null&&!"".equals(text.trim())) {
                                sb.append("【成语】").append(text);
                            }
                        }else{
                            sb.append(text);
                        }
                    }
                }
                sb.append("\r\n");
            }

            document.close();
            //System.out.println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            return sb.toString().replaceAll("\n\\s*【成语】","######");
        }
    }
    public static void toFile() throws Exception{
        StringBuilder sb = new StringBuilder();
        sb.append("<词典>");
        for(int i=0; i<ciTiaos.size(); i++){
            sb.append(ciTiaos.get(i).toString());
        }
        sb.append("</词典>");
        FileUtils.write(new File("D:\\北语项目\\3000成语用法词典W2.xml"), sb.toString(), "utf-8");
    }


    public static void splitCiTiao(String sentence) {
        String[] sentences = sentence
                .replaceAll("\n※","※【义项】")
                .replaceAll("\n\\[反义\\]","※【反义】")
                .replaceAll("\n\\[近义\\]","※【近义】")
                .replaceAll("\n例句","※【例句】")
                .replaceAll("\n【注意】","※【注意】")
                .split("######");
        String regex = "^([^\\s]+)[\\s]+([^\\[]+)\\[([^\\]]+)\\]";
        Pattern ciMuPat = Pattern.compile(regex);
        CiTiao citiao = null;
        System.out.println(sentences.length);
        for(int i = 0; i < sentences.length; i++){
            citiao = new CiTiao();
            System.out.println(i+"---------\t"+sentences[i]);
            String[] segments = sentences[i].split("※");
            for(int j=0; j<segments.length; j++){
                String segment = segments[j].trim();
                if(segment.startsWith("【义项】")){
                    splitYiXiang(segment.replaceAll("【义项】",""),citiao);
                }else if(segment.startsWith("【反义】")){
                    splitFanYi(segment.replaceAll("【反义】",""),citiao);
                }else if(segment.startsWith("【近义】")){
                    splitJinYi(segment.replaceAll("【近义】",""),citiao);
                }else if(segment.startsWith("【例句】")){
                    splitLiju(segment.replaceAll("【例句】",""),citiao);
                }else if(segment.startsWith("【注意】")){
                    citiao.setZhuyi(segment.replaceAll("【注意】",""));
                }else{
                    Matcher mat = ciMuPat.matcher(segment.trim());
                    while(mat.find()){
                        citiao.setCimu(mat.group(1));
                        citiao.setPinyin(mat.group(2));
                        citiao.setJiegou(mat.group(3));
                    }
                }
            }
            ciTiaos.add(citiao);
        }
    }



    public static void splitYiXiang(String segment, CiTiao citiao){
        String[] yixiangs = segment.split("\n");
        YiXiang yixiang = new YiXiang();
        yixiang.setEn_shiyi(yixiangs[0]);
        yixiang.setZh_shiyi(yixiangs[1]);
        citiao.getYixiangList().add(yixiang);
    }

    private static Pattern fanyiPat = Pattern.compile("^\\s*([^（]{3,12})\\s*（([^：）]+)：([^）]+)）\\s*([^\r\n]+)");
    public static void splitFanYi(String segment, CiTiao citiao){
        String[] shilis = segment.split("\n");
        for(int i=0; i<shilis.length; i++) {
            Matcher mat = fanyiPat.matcher(shilis[i]);
            while (mat.find()) {
                FanYi fanyi = new FanYi();
                System.out.println(mat.group(1)+"\t"+mat.group(2)+"\t"+mat.group(3));
                fanyi.setCimu(mat.group(1));
                fanyi.setPinyin(mat.group(2));
                fanyi.setEn_shiyi(mat.group(3));
                citiao.getFanyiList().add(fanyi);
            }
        }
    }

    public static void splitJinYi(String segment, CiTiao citiao){
        String[] shilis = segment.split("\n");
        for(int i=0; i<shilis.length; i++) {
            Matcher mat = fanyiPat.matcher(shilis[i]);
            while (mat.find()) {
                JinYi jinyi = new JinYi();
                jinyi.setCimu(mat.group(1));
                jinyi.setPinyin(mat.group(2));
                jinyi.setEn_shiyi(mat.group(3));
                jinyi.setBijiao(mat.group(4));
                citiao.getJinyiList().add(jinyi);
            }
        }
    }

    private static Pattern pat = Pattern.compile("（[^）]+）$");
    public static void splitLiju(String segment, CiTiao citiao){
        String[] shilis = segment.split("\n");
        for(int i=0; i<shilis.length; i++){
            Shili shili = new Shili();
            Matcher mat = pat.matcher(shilis[i]);
            String text = shilis[i];
            if(mat.find()){
                shili.setJiegou(mat.group(0));
                text = text.replace(mat.group(0),"");
            }
            shili.setText(text);
            citiao.getShilis().add(shili);
        }
    }



}